<template>
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="Params">
        <table class="pure-table wd-100">
          <thead>
            <tr>
              <td>KEY</td>
              <td>VALUE</td>
              <td>DESCRIPTION</td>
            </tr>
          </thead>
          <tbody>
            <template v-for="(item) in request.query" :key="item.name">
              <tr>
                <td>{{item.name}}</td>
                <td>
                  <input v-model="item.value" style="width:100%"/>
                </td>
                <td>
                  {{item.description}}
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="Body">
        <table class="pure-table wd-100">
          <thead>
            <tr>
              <td>KEY</td>
              <td>TYPE</td>
              <td>VALUE</td>
              <td>DESCRIPTION</td>
            </tr>
          </thead>
          <tbody>
            <template v-for="(item) in request.body" :key="item.name">
              <tr>
                <td>
                  {{item.name}}
                </td>
                <td>
                  {{item.type}}
                </td>
                <td>
                  <input v-model="item.value" style="width:100%"/>
                </td>
                <td>
                  {{item.description}}
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </a-tab-pane>
      <a-tab-pane key="3" tab="Path">
        <table class="pure-table wd-100">
          <thead>
            <tr>
              <td>KEY</td>
              <td>VALUE</td>
              <td>DESCRIPTION</td>
            </tr>
          </thead>
          <tbody>
            <template v-for="(item) in request.path" :key="item.name">
              <tr>
                <td>
                  {{item.name}}
                </td>
                <td>
                  <input v-model="item.value" style="width:100%"/>
                </td>
                <td>
                  {{item.description}}
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </a-tab-pane>
      <a-tab-pane key="4" tab="Headers">
        <table class="pure-table wd-100">
          <thead>
            <tr>
              <td>KEY</td>
              <td>VALUE</td>
              <td>DESCRIPTION</td>
            </tr>
          </thead>
          <tbody>
            <template v-for="(item) in request.header" :key="item.name">
              <tr>
                <td>
                  {{item.name}}
                </td>
                <td>
                  <input v-model="item.value" style="width:100%"/>
                </td>
                <td>
                  {{item.description}}
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </a-tab-pane>
    </a-tabs>
    <div>
      <a-button type="primary" block style="margin-top:10px" @click="sendAxios">发送</a-button>
    </div>
    <div>
      <b>响应结果：</b>
      <VueJsonPretty :data="response" />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, unref, watch } from "vue";
import docsObj from "../hooks/docsObj";
import PostManAddMinus from "./PostManAddMinus.vue";
import axios, { Method } from "axios";
import VueJsonPretty from "vue-json-pretty";
import "vue-json-pretty/lib/styles.css";
import { parserParams } from "@/utils/swigger";
import { useSessionStorage } from '@vueuse/core';
export default defineComponent({
  components: {
    PostManAddMinus,
    VueJsonPretty,
  },
  props: {
    requireParams: {
      type: Array,
      default: () => [],
    },
    requireMethod: {
      type: String,
      default: "get",
    },
    url: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    const activeKey = ref("1");
    const request = useSessionStorage<any>(`request_params_${props.url}`, {
      query: [],
      path: [],
      header: [],
      body: {},
    })

    const response = ref({});
    
    // 读取公用的header类型
    const publicHeaders = JSON.parse(localStorage.getItem("__headers") || "[]") as { name: string, value: string, id: string, checked: boolean }[]
    // 公共可用的header
    const avaiHeaders = publicHeaders.filter((item)=>item.checked)
    watch(
      () => props.requireParams,
      (params: any) => {
        const { body, header, path, query } = parserParams(params);
        unref(request).body = body;
        // header 与公共的数据进行处理对比，如果自定义则不会重新赋值
        for(const h of header){
          h.value = avaiHeaders.find(item=> item.name === h.name)?.value
        }
        unref(request).header = header;
        unref(request).path = path;
        unref(request).query = query;
      },
      {
        immediate: true
      }
    );

    const postman = axios.create({});

    postman.interceptors.request.use((config) => {
      console.log(config.responseType);
      return config;
    });

    function sendAxios() {
      console.log(request);
      let url = props.url;
      const data: Record<string, unknown> = {};
      const params: Record<string, unknown> = {};
      const headers: Record<string, string> = {};
      const path: Record<string, string> = {};
      for (const k in unref(request).body) {
        data[k] = unref(request).body[k].value;
      }

      for (const k of unref(request).query) {
        params[k.name] = k.value;
      }

      for (const k of unref(request).header) {
        headers[k.name] = k.value;
      }
      
      // 公用请求头设置
      for(const k of avaiHeaders){
        const ish = unref(request).header.find((item: any)=> item.name === k.name)?.value // 如果请求头存在则不重新设置
        if(ish) continue
        headers[k.name] = k.value;
      }

      if (unref(request).path.length > 0) {
        for (const k of unref(request).path) {
          url = url.replace(`{${k.name}}`, k.value);
        }
      }

      postman({
        url: `http://${unref(docsObj).host}${unref(docsObj).basePath}${url}`,
        method: props.requireMethod as Method,
        data,
        params,
        headers,
      })
        .then((res) => {
          response.value = res.data;
        })
        .catch((error) => {
          delete error.response.config;
          response.value = error.response;
        });
    }

    return {
      request,
      activeKey,
      sendAxios,
      response,
    };
  },
});
</script>